/**
 * @file 日程日历组件
 * @date 2025/11/20
 * @author lyqjob@yeah.net
 */

import { useState, useEffect } from 'react';
import dayjs from 'dayjs';
import { Calendar, Modal, Form, Input, Button, List, Tag, message, Space, Select, Card, Badge, ConfigProvider } from 'antd';
import { CalendarOutlined, UnfoldMoreOutlined } from '@ant-design/icons';
import zhCN from 'antd/locale/zh_CN.js';
import styles from './index.less';

const ScheduleCalendar = () => {
    // 日程相关状态
    const [schedules, setSchedules] = useState([]);
    const [addModalVisible, setAddModalVisible] = useState(false);
    const [viewModalVisible, setViewModalVisible] = useState(false);
    const [selectedDate, setSelectedDate] = useState(null);
    const [selectedDateSchedules, setSelectedDateSchedules] = useState([]);
    const [isExpanded, setIsExpanded] = useState(false); // 控制展开/收起状态
    const [form] = Form.useForm();

    useEffect(() => {
        // 初始化一些模拟数据
        const mockSchedules = [
            {
                id: '1',
                date: dayjs().format('YYYY-MM-DD'),
                title: '团队会议',
                description: '讨论项目进展',
                time: '10:00',
                priority: 'high',
                completed: false
            },
            {
                id: '2',
                date: dayjs().format('YYYY-MM-DD'),
                title: '代码审查',
                description: '审查新功能代码',
                time: '14:00',
                priority: 'medium',
                completed: true
            },
            {
                id: '3',
                date: dayjs().add(1, 'day').format('YYYY-MM-DD'),
                title: '客户演示',
                description: '产品功能演示',
                time: '15:30',
                priority: 'high',
                completed: false
            },
            {
                id: '4',
                date: dayjs().add(2, 'day').format('YYYY-MM-DD'),
                title: '文档编写',
                description: '更新API文档',
                time: '09:00',
                priority: 'low',
                completed: false
            }
        ];
        setSchedules(mockSchedules);
    }, []);

    // 日程管理函数
    const handleAddSchedule = (values) => {
        const newSchedule = {
            id: Date.now().toString(),
            date: selectedDate.format('YYYY-MM-DD'),
            title: values.title,
            description: values.description,
            time: values.time || '全天',
            priority: values.priority || 'medium',
            completed: false
        };
        setSchedules([...schedules, newSchedule]);
        setAddModalVisible(false);
        form.resetFields();
        const dateStr = selectedDate.format('YYYY-MM-DD');
        const daySchedules = [...schedules, newSchedule].filter(schedule => schedule.date === dateStr);
        setSelectedDateSchedules(daySchedules);
        message.success('日程添加成功！');
    };

    const handleDateClick = (date) => {
        setSelectedDate(date);
        const dateStr = date.format('YYYY-MM-DD');
        const daySchedules = schedules.filter(schedule => schedule.date === dateStr);
        setSelectedDateSchedules(daySchedules);
        setViewModalVisible(true);
    };

    const handleDeleteSchedule = (scheduleId) => {
        setSchedules(schedules.filter(schedule => schedule.id !== scheduleId));
        const dateStr = selectedDate.format('YYYY-MM-DD');
        const daySchedules = schedules.filter(schedule => schedule.date === dateStr && schedule.id !== scheduleId);
        setSelectedDateSchedules(daySchedules);
        message.success('日程删除成功！');
    };

    const handleToggleComplete = (scheduleId) => {
        const updatedSchedules = schedules.map(schedule => 
            schedule.id === scheduleId ? { ...schedule, completed: !schedule.completed } : schedule
        );
        setSchedules(updatedSchedules);
        const dateStr = selectedDate.format('YYYY-MM-DD');
        const daySchedules = updatedSchedules.filter(schedule => schedule.date === dateStr);
        setSelectedDateSchedules(daySchedules);
        message.success('日程状态更新成功！');
    };

    const getPriorityColor = (priority) => {
        switch(priority) {
            case 'high': return 'red';
            case 'medium': return 'orange';
            case 'low': return 'green';
            default: return 'blue';
        }
    };

    // 自定义单元格渲染
    const cellRender = (current, info) => {
        if (info.type === 'date') {
            return dateCellRender(current);
        }
        if (info.type === 'month') {
            return monthCellRender(current);
        }
        return info.originNode;
    };

    // 自定义月份单元格渲染
    const monthCellRender = (value) => {
        const monthSchedules = schedules.filter(schedule => schedule.date.startsWith(value.format('YYYY-MM')));
        return (
            <div className={styles.scheduleIndicator}>
                <Badge 
                    status="processing" 
                    style={{ 
                        marginLeft: '4px',
                        marginTop: '2px'
                    }}
                />
            </div>
        );
    };

    // 自定义日期单元格渲染
    const dateCellRender = (value) => {
        const dateStr = value.format('YYYY-MM-DD');
        const daySchedules = schedules.filter(schedule => schedule.date === dateStr);
        
        // 如果没有日程，返回空
        if (daySchedules.length === 0) {
            return null;
        }
        
        // 如果是收起状态，只显示一个点
        if (!isExpanded) {
            return (
                <div className={styles.scheduleIndicator}>
                    <Badge 
                        status="processing" 
                        style={{ 
                            marginLeft: '4px',
                            marginTop: '2px'
                        }}
                    />
                </div>
            );
        }
        
        // 展开状态显示块状标签
        return (
            <div className={styles.scheduleList}>
                {daySchedules.slice(0, 3).map(schedule => (
                    <div 
                        key={schedule.id} 
                        className={`${styles.scheduleTag} ${schedule.completed ? styles.completed : styles[schedule.priority]}`}
                        title={`${schedule.title} - ${schedule.time}`}
                    >
                        {schedule.time && `${schedule.time} `}
                        {schedule.title.length > 10 ? schedule.title.substring(0, 10) + '...' : schedule.title}
                    </div>
                ))}
                {daySchedules.length > 3 && (
                    <div className={styles.moreSchedules}>
                        +{daySchedules.length - 3} 更多
                    </div>
                )}
            </div>
        );
    };

    // 添加日程Modal
    const AddScheduleModal = () => (
        <Modal
            title={`添加日程 - ${selectedDate ? selectedDate.format('YYYY-MM-DD') : ''}`}
            open={addModalVisible}
            onCancel={() => {
                setAddModalVisible(false);
                form.resetFields();
            }}
            footer={null}
        >
            <Form
                form={form}
                layout="vertical"
                onFinish={handleAddSchedule}
            >
                <Form.Item
                    name="title"
                    label="日程标题"
                    rules={[{ required: true, message: '请输入日程标题' }]}
                >
                    <Input placeholder="请输入日程标题" />
                </Form.Item>
                
                <Form.Item
                    name="time"
                    label="时间"
                >
                    <Input placeholder="例如：09:00-10:00 或 全天" />
                </Form.Item>
                
                <Form.Item
                    name="priority"
                    label="优先级"
                    initialValue="medium"
                >
                    <Select>
                        <Select.Option value="high">高</Select.Option>
                        <Select.Option value="medium">中</Select.Option>
                        <Select.Option value="low">低</Select.Option>
                    </Select>
                </Form.Item>
                
                <Form.Item
                    name="description"
                    label="描述"
                >
                    <Input.TextArea rows={3} placeholder="请输入日程描述" />
                </Form.Item>
                
                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit">
                            添加
                        </Button>
                        <Button onClick={() => {
                            setAddModalVisible(false);
                            form.resetFields();
                        }}>
                            取消
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </Modal>
    );

    // 查看日程Modal
    const ViewScheduleModal = () => (
        <Modal
            title={`日程列表 - ${selectedDate ? selectedDate.format('YYYY-MM-DD') : ''}`}
            open={viewModalVisible}
            onCancel={() => setViewModalVisible(false)}
            footer={[
                <Button key="add" type="primary" onClick={() => {
                    setViewModalVisible(false);
                    setAddModalVisible(true);
                }}>
                    添加日程
                </Button>,
                <Button key="close" onClick={() => setViewModalVisible(false)}>
                    关闭
                </Button>
            ]}
        >
            {selectedDateSchedules.length > 0 ? (
                <List
                    dataSource={selectedDateSchedules}
                    renderItem={(schedule) => (
                        <List.Item
                            actions={[
                                <Button 
                                    key="complete" 
                                    type="link" 
                                    onClick={() => handleToggleComplete(schedule.id)}
                                >
                                    {schedule.completed ? '标记未完成' : '标记完成'}
                                </Button>,
                                <Button 
                                    key="delete" 
                                    type="link" 
                                    danger 
                                    onClick={() => handleDeleteSchedule(schedule.id)}
                                >
                                    删除
                                </Button>
                            ]}
                        >
                            <List.Item.Meta
                                title={
                                    <Space>
                                        <span style={{ textDecoration: schedule.completed ? 'line-through' : 'none' }}>
                                            {schedule.title}
                                        </span>
                                        <Tag color={getPriorityColor(schedule.priority)} size="small">
                                            {schedule.priority === 'high' ? '高' : schedule.priority === 'medium' ? '中' : '低'}
                                        </Tag>
                                        {schedule.completed && <Tag color="green">已完成</Tag>}
                                    </Space>
                                }
                                description={
                                    <div>
                                        <div style={{ marginBottom: '4px' }}>
                                            <strong>时间：</strong>{schedule.time}
                                        </div>
                                        {schedule.description && (
                                            <div>
                                                <strong>描述：</strong>{schedule.description}
                                            </div>
                                        )}
                                    </div>
                                }
                            />
                        </List.Item>
                    )}
                />
            ) : (
                <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                    该日期暂无日程
                </div>
            )}
        </Modal>
    );

    return (
        <>
            <Card 
                title={
                    <Space>
                        <CalendarOutlined />
                        <span>日程安排</span>
                    </Space>
                }
                extra={
                    <Button 
                        type="text" 
                        icon={isExpanded ? '无'  : 1}
                        onClick={() => setIsExpanded(!isExpanded)}
                        title={isExpanded ? "收起详情" : "展开详情"}
                    >
                        {isExpanded ? '收起' : '展开'}
                    </Button>
                }
            >
                <ConfigProvider locale={zhCN} style={{height: 400}} >
                    <Calendar 
                        fullscreen={false}
                        cellRender={cellRender}
                        onSelect={handleDateClick}
                        onDoubleClick={(date) => {
                            setSelectedDate(date);
                            setAddModalVisible(true);
                        }}
                    />
                </ConfigProvider>
            </Card>
            <AddScheduleModal />
            <ViewScheduleModal />
        </>
    );
};

export default ScheduleCalendar;